package com.flyqiu.flow.core.var;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.flyqiu.flow.api.script.IVarSerialize;
import com.flyqiu.flow.api.script.FlyQiuFlowVarSerializeManage;
import com.flyqiu.flow.api.script.VarSerialize;

import java.util.Map;

public class JSONObjectConverter implements IVarSerialize {
    private static final String TYPE_KEY = JSONObject.class.getName();

    @Override
    public String type() {
        return TYPE_KEY;
    }

    @Override
    public boolean isType(FlyQiuFlowVarSerializeManage manage, Object val) {
        if (val instanceof JSONObject) {
            return true;
        } else if (val instanceof Map) {
            return true;
        } else if (val instanceof String) {
            return JSON.isValidObject((String) val);
        }
        return false;
    }

    @Override
    public VarSerialize serialize(FlyQiuFlowVarSerializeManage manage, Object val) {
        if (val instanceof JSONObject) {
            return new VarSerialize(TYPE_KEY, ((JSONObject) val).toJSONString(), true);
        } else if (val instanceof Map) {
            return new VarSerialize(TYPE_KEY, JSONObject.toJSONString(val), true);
        } else if (val instanceof String) {
            return new VarSerialize(TYPE_KEY, (String) val, true);
        }
        return null;
    }

    @Override
    public Object deserialize(FlyQiuFlowVarSerializeManage manage, String val) {
        return JSONObject.parseObject(val);
    }
}
